package com.ahwei.shop.auth.security.handler;

import com.ahwei.r.R;
import com.ahwei.shop.auth.entity.User;
import com.ahwei.shop.auth.security.entity.SecurityUser;
import com.ahwei.shop.auth.util.JwtTokenUtil;
import com.ahwei.shop.auth.util.ResponseUtils;
import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author：ahWei
 * Email: ahwei163@qq.com
 * Date: 2022-05-19 17:20:17
 * Description: 身份认证成功处理！
 */
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	@Resource
	private ResponseUtils responseUtils;
	//大胆抛出已检查的异常
	@SneakyThrows
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
		// principal就是UserDetailsService中返回的对象
		SecurityUser securityUser = (SecurityUser)authentication.getPrincipal();
		User currentUser = securityUser.getCurrentUser();
		currentUser.setPassword(null);

		// 根据用户名生成JWT格式的令牌（base64编码的值）
		String token = JwtTokenUtil.generateTokenByRSA(authentication.getName());

		// 准备返回数据
		Map<String, Object> map = new HashMap<>();
		map.put("token", token);
		map.put("user", currentUser);

		// 返回的R对象
		responseUtils.outWriter(R.ok(map), HttpStatus.OK.value(),response);
	}
}